package cn.edu.scau.cmi.chenyiqiu.spring.hibernate.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.chenyiqiu.spring.domain.Student;
import cn.edu.scau.cmi.chenyiqiu.spring.hibernate.factory.HibernateSessionFactory;

public class StudentDao {
	private Session session;
	public Session getSession() {
		if(session==null)
		{
			session=HibernateSessionFactory.getSession();
		}
		return session;
	}
	
	public void save(Student student) {
		getSession();
		Transaction transaction=session.beginTransaction();
		session.save(student);
		transaction.commit();
	}
	
	public void update(Student student) {
		getSession();
		Transaction transaction=session.beginTransaction();
		session.update(student);
		transaction.commit();
	}
	
	public void delete(Student student) {
		getSession();
		Transaction transaction=session.beginTransaction();
		session.delete(student);
		transaction.commit();
	}
	
	public Student findById(Long id) {
		getSession();
		Transaction transaction=session.beginTransaction();
		Student student=(Student) getSession().get(Student.class,id);
		transaction.commit();
		return student;
	}
	
	public List<Student> findAll(){
		String queryString="from Student";
		getSession();
		Transaction transaction=session.beginTransaction();
		Query query=getSession().createQuery(queryString);
		transaction.commit();
		return query.list();
	}
}
